/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dal;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class QuanAoDAL {

    private Connection conn;

    public QuanAoDAL() {
    }

    public ResultSet executeQuery(String sql, Object[] param) {
        ResultSet rs = null;
        try {
            openConnection();
            PreparedStatement statement = setParam(sql, param);
            rs = statement.executeQuery();
        } catch (SQLException ex) {
            System.out.println(">>> QuanAoDAL: " + ex.getMessage());
        }
        return rs;
    }

    public boolean executeUpdate(String sql, Object[] param) {
        try {
            openConnection();
            PreparedStatement statement = setParam(sql, param);
            int rs = statement.executeUpdate();
            if (rs > 0) {
                return true;
            }
        } catch (SQLException ex) {
            System.out.println(">>> QuanAoDAL: " + ex.getMessage());
        } finally {
            closeConnecion();
        }
        return false;
    }

    private PreparedStatement setParam(String sql, Object[] param) throws SQLException {
        PreparedStatement statement = conn.prepareStatement(sql);
        if (param != null) {
            for (int i = 0; i < param.length; i++) {
                statement.setObject(i + 1, param[i]);
            }
        }
        return statement;
    }

    private void openConnection() throws SQLException {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=QuanAoOnline;user=sa;password=123");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(QuanAoDAL.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void closeConnecion() {
        try {
            conn.close();
        } catch (SQLException ex) {
            System.out.println(">>> QuanAoDAL: " + ex.getMessage());
        }
    }
}
